package com.qidian.mes.md.service.impl;

import com.google.gson.Gson;
import com.qidian.mes.md.service.UploadFileService;
import com.qidian.mes.util.pojo.QdResult;
import com.qiniu.common.QiniuException;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.Region;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;

/**
 * @Author: 小可怎么都睡不够
 * @Description:
 * @Time: 2024-04-12 09:12
 **/
@Service
public class UploadFileServiceImpl implements UploadFileService {
    @Value("${accessKey}")
    String accessKey;

    @Value("${secretKey}")
    String secretKey;

    @Value("${bucket}")
    String bucket;

    @Value("${imageAccessBaseUrl}")
    String imageAccessBaseUrl;

    @Override
    public QdResult uploadImage(MultipartFile file) {
        Auth auth = Auth.create(accessKey, secretKey);
        String upToken = auth.uploadToken(bucket);
        Configuration cfg = new Configuration(Region.beimei()); // 北美
        cfg.resumableUploadAPIVersion = Configuration.ResumableUploadAPIVersion.V2;// 指定分片上传版本
        UploadManager uploadManager = new UploadManager(cfg);
        String key = null;
        try {
            Response response = uploadManager.put(file.getBytes(), key, upToken);
            DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
            System.out.println(imageAccessBaseUrl + putRet.hash);
            return QdResult.success("ok", imageAccessBaseUrl + putRet.hash);
        } catch (QiniuException ex) {
            throw new RuntimeException(ex.getMessage());
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}
